package com.stanwind.netty.handler.impl;

import com.stanwind.netty.api.ClientUtils;
import com.stanwind.netty.api.Log;
import com.stanwind.netty.api.RoomUtils;
import com.stanwind.netty.api.TokenUtils;
import com.stanwind.netty.core.protocol.model.Response;
import com.stanwind.netty.domain.model.Character;
import com.stanwind.netty.domain.pojo.Player;
import com.stanwind.netty.domain.pojo.Room;
import com.stanwind.netty.handler.Handler;
import com.stanwind.netty.serialize.GetPlay;
import com.stanwind.netty.serialize.MessageBox;
import com.stanwind.netty.service.CharacterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * Created by StanWind on 2017/2/17.
 * 进入游戏
 */
@Service
@Scope("prototype")
public class GETPLAY extends Handler {
    @Autowired
    private CharacterService characterService;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RoomUtils roomUtils;

    @Autowired
    private ClientUtils clientUtils;

    @Autowired
    private Log log;

    @Override
    public void handle() {
        Response response = new Response();
        GetPlay getPlay = new GetPlay();
        getPlay.readFromBytes(request.getData());
        //首先将玩家信息初始化读入
        String token = getPlay.getToken();
        String accountId = tokenUtils.getAccountIdByToken(token);

        if("".equals(accountId)){
            MessageBox messageBox = new MessageBox();
            messageBox.setMessage("登录已过期,请重新登录");
            messageBox.setState(0);
            response.setTime(0);
            response.setCmd(CMD_MSGBOX);
            response.setData(messageBox.getBytes());
            log.getLogger().info("token 过期--------");

        }else{
            Player player = new Player();
            //设置基本信息
            Character character = this.characterService.selectByAccountId(accountId);
            player.setCharacter(character);
            player.setChannel(getCtx().getChannel());
            player.setOffline(false);
            //加入缓存 判断是否存在
            player = clientUtils.add(player);
            //匹配房间
            Room room = roomUtils.matchRoom(player);

            getPlay.setRoom(room);
            response.setTime(0);
            response.setCmd(CMD_GETPLAY);
            response.setData(getPlay.getBytes());

            log.getLogger().info("play->"+player.toString());
        }
        getCtx().getChannel().write(response);
    }
}
